//
//  ViewController.m
//  kvo
//
//  Created by YuanJiang on 2019/9/5.
//  Copyright © 2019 llbt. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong) UITextField *tf;

@property(nonatomic,strong) UIButton *btn;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tf];
    [self.view addSubview:self.btn];
    
    [self.tf addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"输入框里的值改变了");
    NSLog(@"old key is %@",change[@"old"]);
    NSLog(@"new key is %@",change[@"new"]);
}

-(UITextField *)tf
{
    if (!_tf) {
        _tf = [[UITextField alloc] initWithFrame:CGRectMake(100, 150, [UIScreen mainScreen].bounds.size.width-200, 40)];
        _tf.placeholder = @"请输入一点东西";
        _tf.layer.masksToBounds = YES;
        _tf.layer.borderColor = [UIColor redColor].CGColor;
        _tf.layer.borderWidth = 1.3;
        _tf.layer.cornerRadius = 4;
    }
    return _tf;
}

-(UIButton *)btn
{
    if (!_btn) {
        _btn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [_btn setFrame:CGRectMake(100, 500, [UIScreen mainScreen].bounds.size.width-200, 40)];
        [_btn setTitle:@"按钮" forState:UIControlStateNormal];
        [_btn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        [_btn setBackgroundColor:[UIColor greenColor]];
    }
    return _btn;
}

-(void)clickAction:(UIButton *)sender
{
    NSInteger num = random() % 100;
    NSString *str = [NSString stringWithFormat:@"%ld",(long)num];
    
    [self.tf setText:str];
}

-(void)dealloc
{
    [self.tf removeObserver:self forKeyPath:@"text"];
}

@end
